package com.one.controller;

import com.one.annotation.RequestUser;
import com.one.bean.ProductView;
import com.one.constant.RedisPrefixConstant;
import com.one.service.EsService;
import com.one.util.PageUtil;
import com.one.util.RequestReturn;
import com.one.util.RequestReturnFactory;
import com.one.utils.JedisUtil;
import com.one.vo.UserVo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: EsController
 * @Auther: yph
 * @Date: 2022/1/17 10:08
 * @Description: @Api(tags = "首页搜索查询入口")
 */
@Api(tags = "D.首页搜索查询")
@RestController
public class EsController {

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private EsService esService;

    /**
     * @Author: yph
     * @Date: 2022/1/17 10:08
     * @return:
     * @Description: 首页搜索
     */
//    @ApiResponses({
//            @ApiResponse(code = 1000, message = "SUCCESS", response = RequestReturn.class)
//    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyWord", required = true, value = "搜索关键词"),
            @ApiImplicitParam(name = "pageNo", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "每页容量")
    })
    @ApiOperation(value = "首页搜索", notes = "关键词和分页搜索数据")
    @GetMapping("/searchProduct")
    public RequestReturn<PageUtil<List<ProductView>>> searchProduct(@ApiIgnore @RequestUser UserVo userVo,
                                                                    @RequestParam("keyWord") String keyWord,
                                                                    @RequestParam(value = "pageNo", required = false) Integer pageNo,
                                                                    @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                                    @ApiIgnore HttpSession session) {

        if (pageNo == null || pageNo < 1)
            pageNo = 1;
        if (pageSize == null || pageSize < 1)
            pageSize = 10;
        // 如果用户没有登录 通过通过sessionId 将本地搜索的历史记录放到redis中
        if (Objects.isNull(userVo)) {
            // 获取sessionId
            String sessionId = session.getId();
            addLocalSearchRecords(sessionId, keyWord);
        }
        return RequestReturnFactory.success(
                esService.searchProduct(
                        session.getId(),
                        Objects.isNull(userVo) ? null : userVo.getUserId(),
                        keyWord, pageNo, pageSize));
    }

    /**
     * @Author: yph
     * @Date: 2022/1/18 10:09
     * @return:
     * @Description: 查询搜索历史记录
     */
    @ApiOperation(value = "搜索历史", notes = "按照查询的时间进行排序")
    @GetMapping("/searchRecord")
    public RequestReturn<Map<String, List<String>>> searchRecord(@ApiIgnore @RequestUser UserVo userVo, @ApiIgnore HttpSession session) {

        // 如果用户没有登录 通过通过sessionId
        if (Objects.isNull(userVo)) {
            // 获取sessionId
            String sessionId = session.getId();
            Map<String, List<String>> map = new HashMap<>();
            map.put("searchRecords", searchLocalRecords(sessionId));
            return RequestReturnFactory.success(map);
        }
        // 用户登录状态可以获取userId
        return esService.searchRecord(Objects.isNull(userVo) ? null : userVo.getUserId(), session.getId());
    }

    /**
     * 根据id查询本地的历史记录
     *
     * @param sessionId sessionID
     * @return
     */
    private List<String> searchLocalRecords(String sessionId) {
        return jedisUtil.lrange(RedisPrefixConstant.MOGU_SEARCH_RECORD_NAME + sessionId, 0, -1);
    }

    /**
     * 用户没有登录的时候，将搜索记录添加到redis中 记录sessionId
     *
     * @param sessionId sessionId
     * @param keyWord   关键字
     */
    private void addLocalSearchRecords(String sessionId, String keyWord) {
        // 先判断是否存在该key值 存在就往里面添加信息
        if (jedisUtil.exists(RedisPrefixConstant.MOGU_SEARCH_RECORD_NAME + sessionId)) {
            // 1、先判断是否存在相同的keyWord值 ,如果有直接删除
            jedisUtil.lrem(RedisPrefixConstant.MOGU_SEARCH_RECORD_NAME + sessionId, 1, keyWord);
            // 2、判断redis中现存的数据是否>=5 ，>=5弹出最后一个
            if (jedisUtil.llen(RedisPrefixConstant.MOGU_SEARCH_RECORD_NAME + sessionId) >= 5) {
                // 删除第一条记录
                jedisUtil.rpop(RedisPrefixConstant.MOGU_SEARCH_RECORD_NAME + sessionId);
            }
        }
        // 向尾部添加数据  头在右边
        jedisUtil.lpush(RedisPrefixConstant.MOGU_SEARCH_RECORD_NAME + sessionId, keyWord);
        // 设置有效期为30分钟
        jedisUtil.expire(RedisPrefixConstant.MOGU_SEARCH_RECORD_NAME + sessionId, 1800);
    }

}
